<template>
  <view class="contain_addressbook">
<!--    <nut-tabs v-model="state.tabvalue" background="#fff" auto-height color="#0966ff" class="tabs">-->
<!--      <nut-tab-pane title="发货人" :pane-key="AddressInfoDirection.Sender"></nut-tab-pane>-->
<!--      <nut-tab-pane title="收货人" :pane-key="AddressInfoDirection.Getter"></nut-tab-pane>-->
<!--    </nut-tabs>-->
    <view class="toptabs">
      <view :class="{active: state.tabvalue==AddressInfoDirection.Sender}" @touchStart="changeList(AddressInfoDirection.Sender)">发货人</view>
      <view :class="{active: state.tabvalue==AddressInfoDirection.Getter}" @touchStart="changeList(AddressInfoDirection.Getter)">收货人</view>
    </view>

    <view class="topSearch">
      <nut-input v-model="keyWords" placeholder="请输入姓名/手机号" @update:model-value="changeInput">
        <template #right>
          <Search @click="changeInput"></Search>
        </template>
      </nut-input>
    </view>
    <template v-if="state.tabvalue==AddressInfoDirection.Sender">
      <AddressList :addressList="sendAddressList" @doDefaultAddress="doDefaultAddress" @goSendGoods="goSendGoods"
                   @doEdit="doEdit" @doDelete="doDelete" @doChange="doChange" :isdefault="isSenddefault" />
      <view v-if="sendAddressList===0" class="container_empty">
        <image mode="aspectFit" src="../../assets/images/index/empty1.png"></image>
        <view class="empty_text">暂无地址信息</view>
      </view>
    </template>
    <template v-if="state.tabvalue==AddressInfoDirection.Getter">
      <AddressList :addressList="getAddressList" @doDefaultAddress="doDefaultAddress" @goSendGoods="goSendGoods"
                   @doEdit="doEdit" @doDelete="doDelete" @doChange="doChange" :isdefault="isGetdefault" />
      <view v-if="getAddressList===0" class="container_empty">
        <image mode="aspectFit" src="../../assets/images/index/empty1.png"></image>
        <view class="empty_text">暂无地址信息</view>
      </view>
    </template>

    <view class="newAddress">
      <view class="btn" @click="addAddressNew">
        新增地址
      </view>
    </view>

    <send-form
        :show="showSendForm"
        :type="state.tabvalue"
        :operateType="operateType"
        @close="closeSendForm"
    ></send-form>
  </view>
</template>

<script setup lang='ts'>
import Taro, {useDidShow, useRouter} from "@tarojs/taro";
import {ref} from "vue";
import useAddressInfoStore from "../../store/addressbook";
import useUserInfoStore from "../../store/user";
import useSendGoodsStore from "../../store/sendGoods";
import AddressList from "@/components/pages/addressBook/AddressList.vue";
import {AddressInfoDirection, AddressInfoDirectionCN} from "@/type";
import {AddressInfo} from "@/@api/AddressInfo";
import {Search} from "@nutui/icons-vue-taro";
import sendForm from "@/components/sendForm/index";
import {
  addressBookDelete,
  addressBookUpdate,
  getAddressListSend,
  getMyAddressList, recommandBranch,
  RecommandParam,
  RecommandReturnParam
} from "@/@api";

const state = ref({
  tabvalue: AddressInfoDirection.Sender,
});
const tabvalue = ref()
const router = useRouter()
const isSenddefault = ref("");
const isGetdefault = ref("");
const delId = ref("");
const delVisible = ref(false);
const store = useAddressInfoStore();
const userStore = useUserInfoStore();
const sendStore = useSendGoodsStore();
const sendGoodsStore = useSendGoodsStore()
const keyWords = ref("");

// useDidShow(async () => {
//   if (
//     store.addressEditParameter?.addressDirection == AddressInfoDirection.Sender
//   ) {
//     state.value.tabvalue = AddressInfoDirection.Sender;
//   } else if (
//     store.addressEditParameter?.addressDirection == AddressInfoDirection.Getter
//   ) {
//     state.value.tabvalue = AddressInfoDirection.Getter;
//   }
//   else {
//     state.value.tabvalue = AddressInfoDirection.Sender;
//   }
//
//   //初始化参数
//   //getAddressListInfo();
// });


const oldSendAddressList = ref<AddressInfo[]>([]);
const oldGetAddressList = ref<AddressInfo[]>([]);
const sendAddressList = ref<AddressInfo[]>([]);
const getAddressList = ref<AddressInfo[]>([]);

const showSendForm = ref<boolean>(false)
const operateType = ref<string>('add')

//keywords: keyWords.value
async function getSendList(){
  let data = await getMyAddressList({customerCode:userStore.userInfo.customerCode, infoType: AddressInfoDirection.Sender }) || []
  sendAddressList.value = data ? data.map((item)=>{
    return {...item, isDefaultBool: item.isDefault == item.infoType}
  }) : []
  oldSendAddressList.value = sendAddressList.value
}
async function getReceiveList(){
  let data = await getMyAddressList({customerCode:userStore.userInfo.customerCode, infoType: AddressInfoDirection.Getter }) || []
  getAddressList.value = data || []
  getAddressList.value = data ? data.map((item)=>{
    return {...item, isDefaultBool: item.isDefault == item.infoType}
  }) : []
  oldGetAddressList.value = getAddressList.value
}


function closeSendForm(refresh: boolean) {
  showSendForm.value = false
  if(refresh){
    keyWords.value = ''
    changeList(state.value.tabvalue)
  }
}

function changeList(tabValue: AddressInfoDirection) {
  state.value.tabvalue = tabValue;
  if(tabValue === AddressInfoDirection.Getter){
    getReceiveList()
  }
  else{
    getSendList()
  }
}


useDidShow(()=>{
  if(router.params.type == AddressInfoDirection.Getter){
    state.value.tabvalue = AddressInfoDirection.Getter
  }
  changeList(state.value.tabvalue)
})

//获取地址数据
async function getAddressListInfo() {
  // const res = await $post<{ data: AddressInfo[] }>('/addressManager/addressManager', {
  //     openid: userStore.openid,
  //     type: type
  // })
  const res = await getAddressListSend({
    customerCode: userStore.userInfo.customerCode,
  });
  let sendList = res.filter((item) => {
    return item.infoType === "1" || item.infoType === "3";
  });
  let getList = res.filter((item) => {
    return item.infoType === "2" || item.infoType === "3";
  });
  oldSendAddressList.value = sendList;
  sendAddressList.value = sendList;
  oldGetAddressList.value = getList;
  getAddressList.value = getList;
  const arr = sendAddressList.value.find((item) => {
    return item.isDefault === "1";
  });
  isSenddefault.value = arr?.btcaId as string;

  const getarr = getAddressList.value.find((item) => {
    return item.isDefault === "2";
  });
  isGetdefault.value = getarr?.btcaId as string;


  // if (state.value.tabvalue === AddressInfoDirection.Sender) {
  //   oldSendAddressList.value = sendList;
  //   sendAddressList.value = sendList;
  //
  //   const arr = sendAddressList.value.find((item) => {
  //     return item.isDefault === "1";
  //   });
  //   isSenddefault.value = arr?.btcaId as string;
  // } else {
  //   oldGetAddressList.value = getList;
  //   getAddressList.value = getList;
  //
  //   const arr = getAddressList.value.find((item) => {
  //     return item.isDefault === "True";
  //   });
  //   isGetdefault.value = arr?.btcaId as string;
  // }
  // 搜索
  changeInput();
}

// watch(() => state.value.tabvalue, (newVal) => {
//     getAddressListInfo(newVal)
// })

// 更改默认地址
async function doDefaultAddress(label: string) {
  let params: AddressInfo[] = [];
  if (state.value.tabvalue === AddressInfoDirection.Sender) {
    params = sendAddressList.value.filter((it) => {
      if (it.btcaId === label) {
        return it;
      }
    });
    params[0].isDefault = "1";
  } else {
    params = getAddressList.value.filter((it) => {
      if (it.btcaId === label) {
        return it;
      }
    });
    params[0].isDefault = "2";
  }

  const param = {
    preAdd: params[0].preAdd,
    preAddress: params[0].preAddress,
    preAddressNote: null,
    preArea: null,
    preMobile: null,
    preName: params[0].preName,
    preTel: params[0].preTel,
    infoType: params[0].infoType,
    isDefault: params[0].isDefault,
    email: null,
    customerCode: userStore.userInfo.customerCode,
    btcaId: params[0].btcaId,
  };
  const res = await addressBookUpdate(param);
}
// 去编辑页
function doEdit(item: AddressInfo) {
  if (!store.addressEditParameter) return;
  store.addressEditParameter.addressInfo = item;

  // Taro.navigateTo({
  //   url: "/pages/addressBook/editAddress?type=" + state.value.tabvalue,
  // });
  //改为用抽屉
  operateType.value = 'edit'
  showSendForm.value = true
}
//编辑
async function doChange(item: any) {
  const param = {
    ...item,
    isDefault: item.isDefaultBool?item.infoType:'0'
  }
  const res = await addressBookUpdate(param)
  if(item.infoType === AddressInfoDirection.Sender){
    getSendList()
  }
  if(item.infoType === AddressInfoDirection.Getter){
    getReceiveList()
  }
}
// 删除地址
async function doDelete(id: string) {
  Taro.showModal({
    title: '提示',
    content: '确认删除该地址？',
    success: async(r)=>{
      if(r.confirm){
        const code = await addressBookDelete({ btcaId: id });
        if (code == 200) {
          Taro.showToast({
            icon: "success",
            title: "删除成功",
          })
          changeList(state.value.tabvalue)
        }
      }
    }
  })
}
// 添加地址
function addAddress(val: string) {
  if (!store.addressEditParameter) return;
  store.addressEditParameter.addressInfo = {
    CITY: "",
    EMAIL: null,
    ID: "",
    INFOTYPE: "",
    INPUTTIME: "",
    ISDEFAULT: "",
    NICKNAME: "",
    OPENID: "",
    PREADDRESS: "",
    PREADDRESSNOTE: null,
    PREAREA: "",
    PREMOBILE: "",
    PRENAME: "",
    PRETEL: "",
    PROVINCE: "",
    QUYU: "",
    WEBID: null,
  };
  Taro.navigateTo({
    url: `./editAddress?type=${val}`,
  });
}

function addAddressNew() {
  operateType.value = 'add'
  showSendForm.value = true
}

// 去发货
async function goSendGoods(val: AddressInfo) {
  let pages = Taro.getCurrentPages();
  let prevPage = pages[pages.length - 2]
  //state.value.tabvalue
  if(prevPage.route=="pages/index/mine")
  return
  let addressType = useRouter().params.type == '2' ? '2' : '1'
  sendStore.setSenderGetter(addressType, val)
  // let key = addressType=='1'?'sendAddressInfo':'getAddressInfo'
  // let key2 = addressType=='1'?'sendBranch':'getBranch'
  // let res = await reqGetBranch({
  //   carriagetype: addressType=='1'?"送货":'接货',
  //   province: sendGoodsStore[key].preAdd.split("/")[0],
  //   city: sendGoodsStore[key].preAdd.split("/")[1],
  //   detailaddress: sendGoodsStore[key].preAddress.replace(
  //       sendGoodsStore[key].preAdd.replaceAll("/", ""),
  //       ""
  //   ),
  // });
  // sendGoodsStore[key2].info = res[0];
  // sendGoodsStore[key2].pending = false;
  prevPage.setData({
    chooseAddress: true
  })
  
  console.log(pages,prevPage,"页面");
  
  Taro.navigateBack()
}

// 地址搜索
function changeInput() {
  if(!keyWords.value){
    sendAddressList.value = oldSendAddressList.value
    getAddressList.value = oldGetAddressList.value
  }
  else{
    sendAddressList.value = oldSendAddressList.value.filter((item) => {
      return (
          item.preTel.indexOf(keyWords.value) > -1 ||
          item.preName.indexOf(keyWords.value) > -1
      )
    })
    getAddressList.value = oldGetAddressList.value.filter((item) => {
      return (
          item.preTel.indexOf(keyWords.value) > -1 ||
          item.preName.indexOf(keyWords.value) > -1
      )
    })
  }
}

async function reqGetBranch(
    item: RecommandParam
): Promise<RecommandReturnParam[]> {
  let res = await recommandBranch(item);

  return res;
}




</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
}
.contain_addressbook {
  background-color: #f5f5f5;
  .toptabs {
    width: 100%;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 88rpx;
    border-bottom: 2rpx solid #f5f5f5;
    > view {
      width: 50%;
      font-size: 28rpx;
      color: #666;
      line-height: 88rpx;
      text-align: center;
      position: relative;
      &.active {
        font-size: 32rpx;
        color: #0966ff;
        &:before {
          content: '';
          position: absolute;
          width: 48rpx;
          height: 4rpx;
          top: 72rpx;
          left: calc(50% - 24rpx);
          background-color: #0966ff;
        }
      }
    }
  }
  .header {
    width: 100%;
    background-color: white;
    display: flex;
    justify-content: space-around;
  }

  .tab-list {
    width: 50%;
    text-align: center;
    height: 100rpx;
    font-size: 40rpx;
    line-height: 100rpx;
  }


  .tab-list.active {
    background-color: #fff;
  }


  .topSearch {
    width: 100%;
    height: 96rpx;
    box-sizing: border-box;
    background-color: #fff;
    padding: 12rpx 24rpx;
    .nut-input {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      border-radius: 36rpx;
      background-color: #f5f5f5;
      padding: 0 36rpx;
      input {
        line-height: 72rpx;
        height: 72rpx;
      }
    }
  }

  .newAddress {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 128rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    .btn {
      width: 700rpx;
      height: 88rpx;
      border-radius: 44rpx;
      background-color: #0966ff;
      color: #fff;
      text-align: center;
      line-height: 88rpx;
    }
  }

}

.container_empty {
  width: 80%;
  margin: 280rpx auto;
  text-align: center;

  image {
    width: 300rpx;
    height: 300rpx;
  }
  .empty_text {
    font-size: 32rpx;
    color: #999;
  }
}


</style>
